#coding=utf-8

import struct
import socket

def sendMessage(s, msgID, msg):
    body = msg
    fmt = "!ii" + str(len(body)) + "s"
    packet = struct.pack(fmt, msgID, len(body), body)
    s.send(packet)
    #print 'send msg id', msgID, 'len:', len(body), ' msg:', msg

def receiveMessage(s):
    head=""
    while(len(head) != 8):
        recvLen = 8 - len(head)
        if recvLen == 0:
            break
        try:
            recv = s.recv(recvLen)
            head += recv
        except Exception,e:
            continue

    id, length = struct.unpack("!ii", head)

    fmt = "!ii" + str(length) + "s"
    body = s.recv(length)
    id, length, msg = struct.unpack(fmt, (head + body))
    #print 'recv msg id ',id, ' len', length
    return id, msg

def connect(ip, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
    s.setblocking(1)
    return s

def close(s):
    s.close()

def listen(ip, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((ip, port))
    s.listen(4)
    print 'listening ip:', ip, ' port:', port
    return s

def accept(s):
    conn, addr = s.accept()
    print 'new client connected, addr', addr
    return conn, addr